/*
 * @Author: lduoduo
 * @Date: 2021-04-13 15:32:14
 * @Last Modified by: lduoduo
 * @Last Modified time: 2021-04-23 17:12:45
 * bpmn控制器hooks
 * 流程校验：https://juejin.cn/post/6844904180755202055
 */
import React, { useRef, useEffect } from 'react';

// import EmbeddedComments from 'bpmn-js-embedded-comments';

import { isObject, assign, forEach } from 'min-dash';

import MinimapModule from 'diagram-js-minimap';
import TokenSimulation from 'bpmn-js-token-simulation';
// import lintModule from 'bpmn-js-bpmnlint';

import CustomModeler from '~/components/Custom/CustomModeler';

import { initEventBus, initModelerEvents } from './listeners';
import { fileDownload, setEncoded } from './helper';
import activitiModdleDescriptor from './activiti.json';
import bpmnModdleDescriptor from './bpmn.json';

// import bpmnlintConfig from './.bpmnlintrc';

import BaseModal from '~/components/BaseModal';
import CompHighlight from '../components/Highlight';

const useBook = (props) => {
  const modeler = useRef();

  const start = (divId) => {
    modeler.current = new CustomModeler({
      container: divId,
      keyboard: { bindTo: document },
      // 属性栏容器
      additionalModules: [
        // 小地图
        MinimapModule,
        // 模拟流转模块
        TokenSimulation,
        {
          // paletteProvider: ['value', ''], // 禁用左面板
          // labelEditingProvider: ['value', ''], // 禁用编辑
          // contextPadProvider: ['value', ''], // 禁用点击出现的contextPad
          // bendpoints: ['value', {}], // 禁止流程线变换waypoints
          // zoomScroll: ['value', ''], // 禁止画布滚动
          // moveCanvas: ['value', ''], // 禁止拖拽
        },
        // lintModule,
      ],
      moddleExtensions: {
        activiti: activitiModdleDescriptor,
        bpmn: bpmnModdleDescriptor,
      },
      linting: {
        // bpmnlint: bpmnlintConfig
      },
    });

    const extension = {
      modeling: modeler.current.get('modeling'),
      moddle: modeler.current.get('moddle'),
      eventBus: modeler.current.get('eventBus'),
      bpmnFactory: modeler.current.get('bpmnFactory'),
      elementRegistry: modeler.current.get('elementRegistry'),
      replace: modeler.current.get('replace'),
      selection: modeler.current.get('selection'),
    };

    assign(modeler.current, extension);
    // modeler.current = { ...modeler.current, ...extension };

    window.Modeler = modeler.current;

    // 打开 minimap, 默认不打开
    modeler.current.get('minimap').open();
  };

  const print = (type = 'xml') => () => {
    modeler.current.saveXML({ format: true }).then((e) => {
      // if (type === 'xml') return console.log(e);
      // const t = convert.xml2json(e, { spaces: 2 });
      // console.log(t);

      BaseModal.open({
        title: '打印预览',
        width: 800,
        content: <CompHighlight xml={e.xml} />,
      });
    });
  };

  const download = (type) => () => {
    const Bpmn = modeler.current;

    const fn = type === 'svg' ? 'saveSVG' : 'saveXML';

    Bpmn[fn]({ format: true })
      .then((e) => {
        const d = e.xml || e.svg;
        const { href, filename } = setEncoded(type.toLowerCase(), d);
        fileDownload(href, filename);
      })
      .catch((e) => {
        return console.error(`[useBpmn Warn ]: ${e.message || e}`);
      });
  };

  const redo = () => {
    modeler.current.get('commandStack').redo();
  };

  const undo = () => {
    modeler.current.get('commandStack').undo();
  };

  const loadXml = (xml) => {
    const Bpmn = modeler.current;

    Bpmn.importXML(xml)
      .then(() => {
        initEventBus(Bpmn);
      })
      .catch((err) => {
        console.error('failed to load diagram', err);
      });
  };

  const simulate = () => {
    const mode = modeler.current.get('toggleMode');
    mode.toggleMode();
  };

  // 设置表单
  const setForm = (form) => {};

  return {
    modeler,
    start,
    loadXml,
    print,
    download,
    redo,
    undo,
    setForm,
    simulate,
  };
};

export default useBook;
